from functools import wraps
from typing import Any, Callable
import inspect
import asyncio

from app.utils.response import success_response


def api_response(func: Callable) -> Callable:
    """
    装饰器，确保所有API响应都遵循统一的格式：
    {
        "code": 200,
        "data": {},
        "message": "成功",
        "timestamp": 1234567890
    }
    
    使用方法:
    @api_response
    def my_route_function():
        return {"some": "data"}  # 会被自动包装为标准格式
    """
    @wraps(func)
    async def wrapper(*args, **kwargs) -> Any:
        # 检查函数是否为协程函数
        if inspect.iscoroutinefunction(func):
            result = await func(*args, **kwargs)
        else:
            result = func(*args, **kwargs)
        
        # 如果结果已经是统一格式，则直接返回
        if isinstance(result, dict) and "code" in result and "message" in result and "timestamp" in result:
            return result
            
        # 否则包装为统一格式
        return success_response(data=result)
        
    return wrapper